package com.leadingsoft.controller.download;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.cef.browser.CefBrowser;
import org.cef.callback.CefStringVisitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leadingsoft.common.Constant;
import com.leadingsoft.common.TaskQuene;
import com.leadingsoft.common.model.Hotel;

public class DownloadCtripComment implements CefStringVisitor {
	private static Logger logger = LoggerFactory.getLogger(DownloadCtripComment.class);
	private CefBrowser browser;
	private List<Hotel> hotelList;
	private List<String> hotelIdList;

	public DownloadCtripComment(CefBrowser browser, List<Hotel> hotelList, List<String> hotelIdList) {
		this.browser = browser;
		this.hotelList = hotelList;
		this.hotelIdList = hotelIdList;
	}
	@Override
	public void visit(String string) {
		String url = browser.getURL();
		logger.debug("开始下载当前页面：{}", url);
		// 下载文件保存位置
		StringBuilder filePath = new StringBuilder("/home/ctrip/");
		String index = StringUtils.remove(url, Constant.CTRIPHOTELLISTUTLTEMP);
		filePath.append(index).append(".txt");
		File file = new File(filePath.toString());
		try {
			if (!file.exists() && StringUtils.isNoneBlank(string)) {
				// 开始下载文件
				FileUtils.writeStringToFile(file, string, "UTF-8", false);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 获取酒店评论信息的下一页URL
			String nextUrl = TaskQuene.getCtripHotelCommentListUrl(url, hotelList, hotelIdList);
			if (StringUtils.isEmpty(nextUrl)) {
				TaskQuene.ctripCommentTaskUrl.add(nextUrl.toString());
			} else {
				// 当前任务结束。 关闭浏览器
				browser.close();
			}
		}
	}
}
